package com.itheima.reggie.controller;

import cn.hutool.db.Session;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private HttpSession session;
    //当前项目的POST和PUT请求都是使用请求体传参的  @RequestBody
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        //1.接收前端传入的username，password
        String username = map.get("username");
        String password = map.get("password");
        //调用service查询登录
        ResultInfo resultInfo = employeeService.login(username,password);
        //3.登录成功，将resultinf放入session中
        Employee employee = (Employee) resultInfo.getData();
        session.setAttribute("SESSION_EMPLOYEE", employee);
        //返回
        return resultInfo;
    }
    @PostMapping("/employee/logout")
    public ResultInfo logout(){
        //注销的当前用户的session,不会动的其它session
        session.invalidate();
        //返回成功标识
        return ResultInfo.success(null);
    }
    @GetMapping("/employee/find")
    public ResultInfo find(String name){
        List<Employee> employeeList = employeeService.findByName(name);
        return ResultInfo.success(employeeList);
    }
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){
        employeeService.save(employee);
        return ResultInfo.success(null);
    }
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){
        Employee employee = employeeService.findById(id);
        return ResultInfo.success(employee);
    }
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){
        employeeService.update(employee);
        return ResultInfo.success(null);
    }

}
